package com.iweb.day11;

import com.iweb.entity.Student;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author WuYongheng
 * @date 2021/11/28
 * @description 查询tom的学生信息
 */
public class Test4 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;
        Scanner scanner = new Scanner(System.in);
        // 数据库连接信息
        String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
        String username = "hr";
        String password = "123456";
        try {
            // 加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            // 连接对象
            conn = DriverManager.getConnection(url, username, password);
            if (conn != null) {
                System.out.println("连接成功");
            }
//            System.out.print("请输入学的登录名：");
//            String loginName = scanner.next();

            statement = conn.createStatement();
            String sql = "select studentno,sex,studentname from student " +
                    "where LoginPwd='tom'";
            resultSet = statement.executeQuery(sql);
            // 解析返回数据
            List<Student> gradeList = new ArrayList<>();
            Student student = null;
            while (resultSet.next()) {
                // 获取数据（解析并保存数据）
//                System.out.print(resultSet.getInt("gradeid") + "-"
//                        + resultSet.getString("gradeName"));
//                System.out.println();
                student = new Student();
                student.setLoginPwd(resultSet.getString("loginPwd"));
                student.setSex(resultSet.getInt("sex"));
                student.setStudentName(resultSet.getString("studentName"));
                // 保存到集合
                gradeList.add(student);
            }
            // 查看保存的数据
            for (Student s : gradeList) {
                System.out.println(s.getLoginPwd() + "  " + s.getSex()
                +" "+s.getStudentName());
            }


        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
